package com.mytool.util;

import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 命名工具类
 */
@Component
public class NamingUtil {

    private static final Set<String> PLURAL_EXCEPTIONS = new HashSet<>(Arrays.asList(
            "status", "news", "data", "media", "analytics", "logistics",
            "metadata", "settings", "graphics", "physics", "mathematics"
    ));
    
    /**
     * 将表名转换为领域对象名（驼峰命名，单数形式，首字母大写）
     * 
     * @param tableName 表名
     * @return 领域对象名
     */
    public static String tableToDomainObjectName(String tableName) {
        if (tableName == null || tableName.isEmpty()) {
            return "";
        }
        
        // 移除表名前缀（如t_、tbl_等）
        String name = tableName;
        if (name.matches("^(?:t_|tbl_|tb_).*$")) {
            name = name.replaceAll("^(?:t_|tbl_|tb_)", "");
        }
        
        // 转换为驼峰命名
        StringBuilder result = new StringBuilder();
        boolean nextUpper = true; // 首字母大写
        
        for (int i = 0; i < name.length(); i++) {
            char c = name.charAt(i);
            
            if (c == '_' || c == '-') {
                nextUpper = true;
            } else {
                if (nextUpper) {
                    result.append(Character.toUpperCase(c));
                    nextUpper = false;
                } else {
                    result.append(Character.toLowerCase(c));
                }
            }
        }
        
        // 转换为单数形式
        return pluralToSingular(result.toString());
    }
    
    /**
     * 将复数形式转换为单数形式
     * 
     * @param word 复数形式的单词
     * @return 单数形式的单词
     */
    public static String pluralToSingular(String word) {
        if (word == null || word.isEmpty() || PLURAL_EXCEPTIONS.contains(word.toLowerCase())) {
            return word;
        }
        
        String lower = word.toLowerCase();
        
        // 处理常见的英文复数规则
        if (lower.endsWith("ies") && word.length() > 3) {
            return word.substring(0, word.length() - 3) + "y";
        } else if (lower.endsWith("ses") || lower.endsWith("zes") || lower.endsWith("xes") || 
                  lower.endsWith("ches") || lower.endsWith("shes")) {
            return word.substring(0, word.length() - 2);
        } else if (lower.endsWith("s") && word.length() > 1 && !lower.endsWith("ss")) {
            return word.substring(0, word.length() - 1);
        }
        
        return word;
    }
} 